//通用主页组件
(function ($) {
    "use strict";
    $.fn.bootstrapTableExtension = function (options, param) {

        var target = $(this);
        // 如果是调用方法
        if (typeof options === 'string') {
            return $.fn.bootstrapTableExtension.methods[options](this, param);
        }
        // 如果是初始化组件
        options = $.extend({}, $.fn.bootstrapTableExtension.defaults, options || {});
        //工具栏开始
        var html = '';
        if (options.isShowToolbar) {
            html += ('<div id="' + options.toolbar + '"><div class="btn-group">');
            //添加按钮
            html += (options.isAddBtnIsShow ? '<button type="button" id="btn-add" class="btn btn-success"><i class="glyphicon glyphicon-plus"></i>' + options.addBtnText + '</button>' : '');
            //修改按钮
            html += (options.isEditBtnIsShow ? '<button type="button" id="btn-edit" class="btn btn-warning"><i class="glyphicon glyphicon-edit"></i>' + options.editBtnText + '</button>' : '');
            //删除按钮
            html += (options.isDeleteBtnIsShow ? '<button type="button" id="btn-delete" class="btn btn-danger"><i class="glyphicon glyphicon-remove"></i>' + options.deleteBtnText + '</button>' : '');

            //其它按钮
            if (typeof options.otherButtons !== "undefined" && options.otherButtons.length > 0) {
                options.otherButtons.forEach(function (item) {
                    html += item.isShow ? '<button type="button" id="' + item.id + '" class="' + item.classes + '""><i class="' + item.iconClasses + '"></i>' + item.text + '</button>' : '';
                });
            }
            html += '</div>';

            //下拉筛选
            if (typeof options.otherSelects !== "undefined" && options.otherSelects.length > 0) {
                options.otherSelects.forEach(function (item) {
                    if (item.isShow && item.data.length > 0) {
                        html += '<select id="' + item.id + '" name="' + item.name + '" class="' + item.classes + '" style="width: auto;display: inline;vertical-align: middle;margin-left: 10px;">';
                        item.data.forEach(function (data) {
                            html += '<option value="' + data.value + '">' + data.name + '</option>';
                        });
                        html += '</select>';
                    }
                });
            }

            //输入框搜索
            if (typeof options.otherInputs !== "undefined" && options.otherInputs.length > 0) {
                options.otherInputs.forEach(function (item) {
                    html += item.isShow ? '<input style="width: auto;display: inline;vertical-align: middle;margin-left: 10px;" type="text" name="' + item.name + '" id="' + item.id + '" class="form-control" placeholder="' + item.placeholder + '">' : '';
                });
            }
            html += '</div>';
            this.append(html);
        }
        //工具栏结束
        var tableHtml = '<div class="table-responsive"><table class="table" id="' + options.tableId + '"></table></div>';
        this.append(tableHtml);

        options.tableInfo.url = options.dataUrl;
        options.tableInfo.toolbar = '#' + options.toolbar;
        options.tableInfo.columns = options.columns;
        options.tableInfo.id = options.dataId;
        options.tableInfo.parentCode = options.parentCode;
        options.tableInfo.code = options.treeTableCode;
        options.tableInfo.saveStateName = options.saveStateName;
        options.tableInfo.saveState = options.saveState;
        options.tableInfo.singleSelect = options.singleSelect;
        options.tableInfo.sortName = options.sortName;
        options.tableInfo.sortOrder = options.sortOrder;
        options.tableInfo.search = options.search;
        options.tableInfo.pagination = options.pagination;
        //固定列
        if (options.fixedColumns) {
            options.tableInfo.fixedColumns = options.fixedColumns;
        }
        if (options.fixedNumber) {
            options.tableInfo.fixedNumber = options.fixedNumber;
        }
        if (options.fixedRightNumber) {
            options.tableInfo.fixedRightNumber = options.fixedRightNumber;
        }
        if (!options.isShowToolbar) {
            options.tableInfo.showExport = false;
            options.tableInfo.showPrint = false;
            options.tableInfo.showRefresh = false;
            options.tableInfo.showColumns = false;
        }
        //bootstrap-table表格筛选
        options.tableInfo.queryParams = function (arg) {
            var inputs = $(target.find('#' + options.toolbar).find('input[type=text]'));
            var i = 0;
            while (true) {
                if (inputs[i] === undefined) {
                    break;
                }
                var input = $(inputs[i]);
                var v = input.val();
                if (v !== undefined && v !== '') {
                    arg[input.attr('name')] = v;
                }
                i++;
            }

            var selects = $(target.find('#' + options.toolbar).find('select'));
            var j = 0;
            while (true) {
                if (selects[j] === undefined) {
                    break;
                }
                var select = $(selects[j]);
                var sv = select.val();
                if (sv !== undefined && sv !== '') {
                    arg[select.attr('name')] = sv;
                }
                j++;
            }
            return arg;
        };
        if (options.height > 0) {
            options.tableInfo.height = options.height;
        }

        if (typeof options.type !== "undefined" && options.type === 'tree') {
            $.fn.bootstrapTableExtension.table = target.find('.table-responsive').find('#' + options.tableId).bootstrapTreeTable(options.tableInfo);
        } else {
            $.fn.bootstrapTableExtension.table = target.find('.table-responsive').find('#' + options.tableId).bootstrapTable(options.tableInfo);
        }

        //工具栏事件
        target.find('#' + options.toolbar + '').find('.btn-group').find('#btn-add').click(function (event) {
            $.fn.bootstrapTableExtension.layerIndex = layer.open({
                type: 2,
                title: '添加数据',
                shadeClose: true,
                shade: 0.8,
                maxmin: true,
                area: ['90%', '90%'],
                content: options.addUrl //iframe的url
            });
        });
        target.find('#' + options.toolbar + '').find('.btn-group').find('#btn-edit').click(function (event) {
            var obj = typeof options.type !== "undefined" && options.type === 'tree' ? $.fn.bootstrapTableExtension.table.bootstrapTreeTable('getSelections') : $.fn.bootstrapTableExtension.table.bootstrapTable('getSelections');
            if (obj.length < 1) {
                layer.msg('请勾选要编辑的数据', {icon: 5});
                return false;
            }
            if (obj.length > 1) {
                layer.msg('编辑数据只可以勾选一条记录', {icon: 5});
                return false;
            }

            $.fn.bootstrapTableExtension.layerIndex = layer.open({
                type: 2,
                title: '修改信息',
                shadeClose: true,
                shade: 0.8,
                maxmin: true,
                area: ['90%', '90%'],
                content: options.editUrl + '/' + obj[0][options.dataId] //iframe的url
            });
        });
        target.find('#' + options.toolbar + '').find('.btn-group').find('#btn-delete').click(function (event) {
            var obj = typeof options.type !== "undefined" && options.type === 'tree' ? $.fn.bootstrapTableExtension.table.bootstrapTreeTable('getSelections') : $.fn.bootstrapTableExtension.table.bootstrapTable('getSelections');
            if (obj.length < 1) {
                layer.msg('请勾选要删除的数据', {icon: 5});
                return false;
            }
            var ids = [];
            for (var i = 0; i < obj.length; i++) {
                ids.push(obj[i][options.dataId]);
            }
            layer.confirm('要删除选中的数据？', {
                btn: ['是', '否'] //按钮
            }, function () {
                $.post(options.delUrl, {
                    ids: ids
                }, function (data) {
                    if (data.status) {
                        if (typeof options.type !== "undefined" && options.type === 'tree') {
                            window.location.reload();
                        } else {
                            $.fn.bootstrapTableExtension.table.bootstrapTable('refresh');
                        }
                        layer.msg(data.msg, {icon: 1});
                    } else {
                        layer.msg(data.msg, {icon: 2});
                    }
                });
            });
        });

        //其它按钮事件
        if (typeof options.otherButtons !== "undefined" && options.otherButtons.length > 0) {
            options.otherButtons.forEach(function (item) {
                if (item.isShow) {
                    target.find('#' + options.toolbar + '').find('.btn-group').find('#' + item.id).click(function () {
                        item.btnEvent();
                    });
                }
            });
        }

        //输入框搜索事件
        if (typeof options.otherInputs !== "undefined" && options.otherInputs.length > 0) {
            target.find('#' + options.toolbar + '').find('input[type=text]').change(function () {
                if (typeof options.type !== "undefined" && options.type === 'tree') {
                    var arg = {};
                    var inputs = $(target.find('#' + options.toolbar).find('input[type=text]'));
                    var i = 0;
                    while (true) {
                        if (inputs[i] === undefined) {
                            break;
                        }
                        var input = $(inputs[i]);
                        var v = input.val();
                        if (v !== undefined && v !== '') {
                            arg[input.attr('name')] = v;
                        }
                        i++;
                    }

                    var selects = $(target.find('#' + options.toolbar).find('select'));
                    var j = 0;
                    while (true) {
                        if (selects[j] === undefined) {
                            break;
                        }
                        var select = $(selects[j]);
                        var sv = select.val();
                        if (sv !== undefined && sv !== '') {
                            arg[select.attr('name')] = sv;
                        }
                        j++;
                    }
                    $.fn.bootstrapTableExtension.table.bootstrapTreeTable('refresh', arg);
                } else {
                    $.fn.bootstrapTableExtension.table.bootstrapTable('selectPage', 1);
                }
            });
        }

        if (typeof options.otherSelects !== "undefined" && options.otherSelects.length > 0) {
            target.find('#' + options.toolbar + '').find('select').change(function () {
                if (typeof options.type !== "undefined" && options.type === 'tree') {
                    var arg = {};
                    var inputs = $(target.find('#' + options.toolbar).find('input[type=text]'));
                    var i = 0;
                    while (true) {
                        if (inputs[i] === undefined) {
                            break;
                        }
                        var input = $(inputs[i]);
                        var v = input.val();
                        if (v !== undefined && v !== '') {
                            arg[input.attr('name')] = v;
                        }
                        i++;
                    }

                    var selects = $(target.find('#' + options.toolbar).find('select'));
                    var j = 0;
                    while (true) {
                        if (selects[j] === undefined) {
                            break;
                        }
                        var select = $(selects[j]);
                        var sv = select.val();
                        if (sv !== undefined && sv !== '') {
                            arg[select.attr('name')] = sv;
                        }
                        j++;
                    }
                    $.fn.bootstrapTableExtension.table.bootstrapTreeTable('refresh', arg);
                } else {
                    $.fn.bootstrapTableExtension.table.bootstrapTable('selectPage', 1);
                }
            });
        }
        return $.fn.bootstrapTableExtension.table;
    };

    $.fn.bootstrapTableExtension.layerIndex = 0;
    $.fn.bootstrapTableExtension.table = null;

    $.fn.bootstrapTableExtension.methods = {
        close: function () {
            if ($.fn.bootstrapTableExtension.layerIndex > 0) {
                layer.close($.fn.bootstrapTableExtension.layerIndex);
            }
        },
        edit: function (target, url) {
            $.fn.bootstrapTableExtension.layerIndex = layer.open({
                type: 2,
                title: '修改信息',
                shadeClose: true,
                shade: 0.8,
                maxmin: true,
                area: ['90%', '90%'],
                content: url //iframe的url
            });
        },
        newLayer: function (target, params) {
            $.fn.bootstrapTableExtension.layerIndex = layer.open({
                type: 2,
                title: params.title,
                shadeClose: true,
                shade: 0.8,
                maxmin: true,
                area: ['90%', '90%'],
                content: params.url //iframe的url
            });
        }
    };

    $.fn.bootstrapTableExtension.defaults = {
        type: 'table',//表格类型（table：普通表格、tree：树形表格）
        dataUrl: '/sys/user/list',//数据加载地址
        addUrl: '/sys/user/add',
        editUrl: '/sys/user/edit',//菜单编辑地址
        isAddBtnIsShow: false,
        addBtnText: '添加',
        isEditBtnIsShow: false,
        editBtnText: '编辑',
        isDeleteBtnIsShow: false,
        deleteBtnText: '删除',
        delUrl: '/sys/user/delete',//删除数据地址
        isShowToolbar: true,
        toolbar: 'toolbar',//工具栏
        columns: [],
        height: 0,
        singleSelect: false,//是否单选
        sortName: 'id',
        sortOrder: 'asc',
        search: true,
        dataId: 'id',//数据主键
        parentCode: 'parentId',
        treeTableCode: 'id',
        saveStateName: 'tree-grid-state-menu',
        saveState: true,
        pagination: true,
        fixedColumns: true,
        fixedNumber: 2,
        fixedRightNumber: 0,
        tableId: 'bs-table',
        tableInfo: {
            resizable: true,
            reorderableColumns: true,
            columns: [],
            classes: 'table table-striped table-hover table-no-left-right-border',
            pageSize: 10,//每页条数,
            pageList: [1, 2, 4, 10, 20, 50, 100],//条数可选
            pagination: true,//是否显示分页
            paginationShowPageGo: true,//是否显示跳转到指定页码
            sidePagination: 'server',
            queryParamsType: 'page',
            search: true,//是否显示搜索
            toolbar: '#toolbar',//工具栏
            responseHandler: function (argument) {
                console.log(argument);
                if (typeof argument.rows == "undefined") {
                    argument.rows = argument.records;
                }
                return argument;
            },
            escape: false,//是否对富文本进行转义
            searchOnEnterKey: false,//设置为 true时，按回车触发搜索方法，否则自动触发搜索方法。
            searchText: '',//初始化搜索文字。
            searchTimeOut: 500,//毫秒，搜索超时时间
            trimOnSearch: true,//搜索是否去除两边空格
            showColumns: true,//是否显示内容列下拉框
            showRefresh: true,//是否显示刷新按钮
            clickToSelect: true,//点击行选中
            singleSelect: false,//是否单选
            sortName: 'id',//默认排序字段
            sortOrder: 'desc',
            showExport: true,//是否显示导出按钮
            exportTypes: ['excel', 'doc', 'png'],//要导出文件的格式，导出PDF时，中文出现乱码
            exportOptions: {
                ignoreColumn: [0],  //忽略某一列的索引
                fileName: '数据列表',  //文件名称设置
                worksheetName: 'sheet1',  //表格工作区名称
                tableName: '数据列表'
            },//导出数据选项
            showPrint: true,//是否显示打印按钮

            //treeTable参数
            id: 'id',// 选取记录返回的值
            code: 'id',// 用于设置父子关系
            parentCode: 'parentId',// 用于设置父子关系
            rootCodeValue: "",//设置根节点code值----可指定根节点，默认为null,"",0,"0"
            type: 'get',//请求数据的ajax类型
            expandColumn: 1,//在哪一列上面显示展开按钮,从0开始
            striped: true,   //是否各行渐变色
            expandAll: true,  //是否全部展开
            expanderExpandedClass: 'glyphicon  glyphicon-triangle-bottom',
            expanderCollapsedClass: 'glyphicon glyphicon-triangle-right',
            saveState: true,
            saveStateName: 'tree-grid-state-menu'
        },
        //其它的按钮
        otherButtons: [
            // {
            //     isShow: true,
            //     classes: 'btn btn-success',
            //     iconClasses: 'glyphicon glyphicon-plus',
            //     text: '测试其它按钮',
            //     id: 'btn-test',
            //     btnEvent: function () {
            //         console.log('测试其它按钮事件');
            //     }
            // }
        ],//下拉筛选框
        otherSelects: [
            // {
            //     isShow: true,
            //     classes: 'form-control',
            //     name: 'roleId',
            //     id: 'roleId',
            //     data: [
            //         {
            //             value: '',
            //             name: '-- 请选择角色 --'
            //         }, {
            //             value: 1,
            //             name: '-- 超级管理员 --'
            //         }, {
            //             value: 13,
            //             name: '-- 普通管理员 --'
            //         }
            //     ]
            // }
        ],//其它的搜索框
        otherInputs: [
            // {
            //     isShow: true,
            //     classes: 'form-control',
            //     name: 'search',
            //     id: 'search',
            //     placeholder: '请输入文字并回车查询'
            // }
        ],
    }
})(jQuery);
